<template>
  <ul class="w-tree">
    <template v-if="treeData.length > 0">
      <template v-for="(item, index) in treeData" :key="index">
        <w-tree-node
          :tree-data="item"
          :default-expand="defaultExpand"
          :w-node="wNode"
          :w-key="wKey"
          :w-children="wChildren"
          @expand="onExpand"
        >
          <template #showIcon>
            <slot name="showIcon">
              <show-icon />
            </slot>
          </template>
        </w-tree-node>
      </template>
    </template>
    <template v-else>
      <slot name="noData">
        <span>暂无数据</span>
      </slot>
    </template>
  </ul>
</template>

<script lang="ts">
import { defineComponent, PropType, DefineComponent } from "vue";
import { TreeData } from "../wtree/type";
import WTreeNode from "./wtreeNode.vue";
import DefaultNode from "./defaultNode.vue";
import ShowIcon from "./showIcon.vue";
export default defineComponent({
  name: "w-tree",
  components: {
    WTreeNode,
    ShowIcon,
  },
  props: {
    /** 数据源 */
    treeData: {
      type: Array as PropType<Array<TreeData>>,
      required: true,
      default: () => {
        return [];
      },
    },
    /** 需要展开的 节点key */
    defaultExpand: {
      required: false,
      type: Array as PropType<Array<string>>,
      default: () => {
        return [];
      },
    },
    /** 自定义渲染 */
    wNode: {
      type: Object as PropType<DefineComponent>,
      default: () => {
        return DefaultNode;
      },
    },
    /** 自定义Key 字段 */
    wKey: {
      type: String,
      default: "key",
    },
    /** 自定义children 字段 */
    wChildren: {
      type: String,
      default: "children",
    },
  },
  /** 展开节点 自定义事件 */
  emits: ["expand"],
  setup: (props, { emit }) => {
    const onExpand = (treeData: TreeData) => {
      emit("expand", treeData);
    };
    return { onExpand };
  },
});
</script>

<style scoped lang="less">
.w-tree {
  text-align: left;
  margin: 0;
  padding: 0;
  user-select: none;
  width: 100%;
  list-style: none;
}
</style>
